package com.fenghongzhang.day016;

import androidx.appcompat.app.AppCompatActivity;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {
    private Button play;

    private MediaPlayer mediaPlayer ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        play = (Button) findViewById(R.id.play);
        mediaPlayer = new MediaPlayer();

        play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //可以是网址,也可以是本地文件的地址
                try {
                    mediaPlayer.reset();
                    mediaPlayer.setDataSource("http://m10.music.126.net/20201027150308/320a0e3526ea63b1b6a8777ca7961786/ymusic/020c/060e/5209/5ff559b7611d1e16ed0dec6092983272.mp3");
//                    mediaPlayer.prepare();
                    //异步准备
                    mediaPlayer.prepareAsync();
                    mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                        @Override
                        public void onPrepared(MediaPlayer mp) {
                            mediaPlayer.start();
                        }
                    });

                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        });

    }

    public void pause(View view) {
        mediaPlayer.pause();
    }

    public void restart(View view) {
        mediaPlayer.start();
    }

    public void stop(View view) {
        mediaPlayer.stop();
    }
}
